if (!localStorage.getItem("token")) {
  localStorage.setItem("uid", "73875")
  localStorage.setItem("token", "69b3ec3750ae8b27194360c369a13b6f")
  localStorage.setItem("username", "刘一涵")
}

let uid = localStorage.getItem("uid")

use()

function use() {
  let username = localStorage.getItem("username")
  if (username) {
    $(".user").html(`Hi，<span>${username}</span>
    <ul>
    <li>个人信息<span class="iconfont icon-youjiantou"></span></li>
    <li>我的订单<span class="iconfont icon-youjiantou"></span></li>
    <li>我的收藏夹<span class="iconfont icon-youjiantou"></span></li>
    <li class="useOut">登出<span class="iconfont icon-youjiantou"></span></li>
    </ul>
    `)
    $(".useOut").click(function () {
      layer.confirm('退出当前登录用户, 是否继续?', {
        icon: 3,
        title: '提示'
      }, function (index) {
        //do somethingZ
        //点确定要执行的代码
        layer.close(index);
        localStorage.removeItem("username")
        localStorage.removeItem("uid")
        localStorage.removeItem("token")
        $(".user").html("<span>登录</span>")
      })
      return false
    })

  } else {
    $(".user").html("<span>登录</span>")
  }
}

//  获取头部的的列表数据
let headObj = obj
var headListArr = headObj.menuDataList;
//   console.log(headListArr);

//  定义 headList_layer_1_HTML 变量 获取一级列表的内容
let headList_layer_1_HTML = "";

//  定义 headList_layer_2_imgBox 存放二级列表 图片及图片描述
let headList_layer_2_imgBoxHtml = "";
headList_layer_2_ul = "";

//    定义 headList_layer_3_ul 保存三级ul 标头
let headList_layer_3_ul = "";

//    定义 KIEHLS_text  变量 保存品牌历史
let KIEHLS_text = "";

//     循环遍历列表取出数据
headListArr.forEach((headList_layer_1_obj, i) => {
  // console.log(headList_layer_1_obj);

  //  将一级列表内容生成
  headList_layer_1_HTML += `
                                 <li i="${i}" class="headList_layer_1">
                                   <a href="javascript:;">${headList_layer_1_obj.label}</a>
                                   <div class="headListHover"><div class="headListHover-cont"></div></div>
                                 </li>
                               `;
  //  把一级列表内容写入一级ul
  $(".headList").html(headList_layer_1_HTML);

  if (headList_layer_1_obj.childList.length >= 1) {
    //   console.log(i);

    //    获取二级列表的父元素
    let parent_layerArr = document.querySelectorAll(".headList_layer_1");
    //   console.log(parent_layerArr);
    let parent_layer = parent_layerArr[i];

    //    获取二级列表
    let headList_layer_2_Arr = headList_layer_1_obj.childList;
    //   console.log(headList_layer_2_Arr);

    //    遍历二级列表
    headList_layer_2_Arr.forEach((headList_layer_2_obj) => {
      //  取出三级列表内容
      //    console.log(headList_layer_2_obj);
      if (
        headList_layer_2_obj !=
        headList_layer_2_Arr[headList_layer_2_Arr.length - 1]
      ) {
        //  获得二级标题
        //   console.log(headList_layer_2_obj);
        if (headList_layer_2_obj.label == " ") {} else {
          headList_layer_2_ul += `
                                       <ul class="headList_layer_2_title" i="${i}">
                                           <h2>${headList_layer_2_obj.label}</h3>
                                           </ul>
                               `;
          let headList_layer_2_title = document.querySelector(
            ".headList_layer_2_title"
          );
          headList_layer_2_title.innerHTML = headList_layer_2_ul;
        }
        //    得到三级列表数组
        let headList_layer_3_Arr = headList_layer_2_obj.childList;
        //   console.log(headList_layer_3_Arr);
        //      遍历三级
        headList_layer_3_Arr.forEach((headList_layer_3_obj) => {
          // console.log(headList_layer_3_obj);
          if (headList_layer_3_obj.parentLabel == " ") {
            headList_layer_3_obj.parentLabel = "上市新品";
          }
          if (i == 5 && headList_layer_3_obj.parentLabel == "按肤质") {
            headList_layer_3_obj.parentLabel = "按发质";
          }
          // console.log(headList_layer_3_obj.label);
          headList_layer_3_ul += `        <li parentLabel="${headList_layer_3_obj.parentLabel}" class="headList_layer_3_ul" i="${i}">
                                           ${headList_layer_3_obj.label}
                                           </li>
                                   `;

          let headList_layer_3 = document.querySelector(".headList_layer_3");
          headList_layer_3.innerHTML = headList_layer_3_ul;
        });
      }

      //  取出二级图片及内容
      //  最后一个obj存放图片及图片内容
      else if (
        (headList_layer_2_obj =
          headList_layer_2_Arr[headList_layer_2_Arr.length - 1])
      ) {
        //  console.log(headList_layer_2_obj.childList);
        headList_layer_2_obj.childList.forEach((KIEHLS_Obj) => {
          //    console.log(KIEHLS_Obj.label);
          // 取出品牌历史内容
          KIEHLS_text += `<li class="kiehls_text" i="${i}">${KIEHLS_Obj.label}</li>`;
          let kiehls_text = document.querySelector(".kiehls_text");
          kiehls_text.innerHTML = KIEHLS_text;
        });
        //  判断是否有图片
        if (headList_layer_2_obj.imageUrl) {
          // console.log("这是图片");
          //  获得图片链接
          // console.log(headList_layer_2_obj.imageUrl);
          //  获取图片内容
          // console.log(headList_layer_2_obj.parentLabel);

          // 将获取的二级内容放入模板字符串
          headList_layer_2_imgBoxHtml += `  <div i="${i}" class="headList_layer_2_imgBox">
                                           <img i=${i} src="${headList_layer_2_obj.imageUrl}">
                                           <p>${headList_layer_2_obj.title}</p>
                                           </div>`;
          // 将二级菜单 图片存入  .headList_layer_2
          $(".headList_layer_2").html(headList_layer_2_imgBoxHtml);
        }
      }
    });
  }
});

//  合并二级标题数据
$(".headList_layer_2_title").attr("i", function (i) {
  // console.log($(".headList_layer_1").eq($(this).attr("i")));
  $(".headList_layer_1")
    .eq($(this).attr("i"))
    .find(".headListHover-cont")
    .append(this);
  // $(".headList_layer_1").eq($(this).attr("i")).append(this)
  // console.log($(".headList_layer_1").eq($(this).attr("i")));
});

// 合并三级数据到二级标头内部
let d = document.querySelectorAll(".headList_layer_2_title>h2");
//  console.log(d);
d.forEach((t) => {
  // console.log($(t).text());
  $(".headList_layer_3_ul").attr("parentLabel", function (index) {
    //  console.log($(this).attr("i"),$(t.parentNode).attr("i"));
    if (
      $(this).attr("parentLabel") == $(t).text() &&
      $(this).attr("i") == $(t.parentNode).attr("i")
    ) {
      // console.log(t);
      $(t.parentNode).append($(this)[0]);
      // console.log(this, t);
    }
  });
});

//  合并其他数据
//  console.log();

console.log($(".headList .headList_layer_1:eq(0)"));
$("<ul></ul>").appendTo(
  $(".headList .headList_layer_1:eq(0)").find(".headListHover-cont")
);
$(".headList .headList_layer_1:eq(0)")
  .find("ul")
  .append($(".headList_layer_3").children());

//  $(".kiehls_text").children();

//  console.log($(".headList .headList_layer_1:eq(6)"));
$(".headList .headList_layer_1:eq(6)")
  .find(".headListHover-cont")
  .append($(".kiehls_text").children());

//  合并二级图片数据
$(".headList_layer_2_imgBox").attr("i", function (i) {
  // console.log($(this).attr("i"));
  $(".headList_layer_1")
    .eq($(this).attr("i"))
    .find(".headListHover-cont")
    .append(this);
  // console.log($(".headList_layer_1").eq($(this).attr("i")));
});
// console.log($(".headList_layer_1:eq(1)"));
$(".headList_layer_1").eq(1).find(".headListHover").remove();
$(".headList_layer_1").eq(7).find(".headListHover").remove();

// ——————————————————————————————————————分割线————————————————————————————————————
// ——————————————————————————————————————分割线————————————————————————————————————
// ——————————————————————————————————————分割线————————————————————————————————————
// ——————————————————————————————————————分割线————————————————————————————————————
//  js样式

//    二级菜单样式
let outwidth = $(window).outerWidth();
// console.log($(window).outerWidth());
$(".headListHover").outerWidth(outwidth);
$(".headListHover-cont").outerWidth(outwidth);
// console.log($(".headListHover").outerWidth());
// console.log($(".headListHover-cont").outerWidth());
$(".headList").offset();
console.log($(".headList").offset().left);
$(".headListHover").css("left", -$(".headList").offset().left);
window.onresize = function () {
  let outwidth = $(window).outerWidth();
  console.log($(window).outerWidth());
  $(".headListHover").outerWidth(outwidth);
  $(".headListHover-cont").outerWidth(outwidth);
  console.log($(".headListHover").outerWidth());
  console.log($(".headListHover-cont").outerWidth());
  $(".headList").offset();
  console.log($(".headList").offset().left);
  $(".headListHover").css("left", -$(".headList").offset().left);
};

// nav滚动样式

$(".headList").prepend(
  $(
    '<li class="imgLi LiHover"><img src="https://www.kiehls.com.cn/img/logo.8364d531.png" /></li>'
  )
);

$(".imgLi>img").css({
  width: "110px"
});

$(".headList").append(
  $(
    '<li class="inputLi LiHover"><input placeholder="高保湿霜"><div class="inline"><span class="iconfont icon-sousuo"></span></div></li>'
  )
);

$(".inputLi")
  .css({
    width: "110px",
    position: "relative"
  })
  .find("input")
  .css({
    width: "70%",
    display: "inline-black"
  });
$(".inputLi").find(".inline").css({
  display: "inline-block",
  width: "30px",
  background: "#FFF",
  height: "17.7px",
  position: "absolute",
  top: "15.5px",
  right: "10px",
  border: "none",
});
$(".inputLi .inline").find("span").css({
  fontSize: "16px",
  lineHeight: "20px",
  position: "absolute",
  right: "1px",
});
$(".headList").append(
  $(
    `<li class="cartLi LiHover"><span class="iconfont icon-gouwudai101"></span>
    <div class="navCartHover">
      <div class="left left-wrap">
        <p  class="empty-title">您的购物车为空</p>
                    <a>
                      <p  class="go-shopping">立即选购您喜欢的商品</p>
                    </a>
      </div>
      <div class="right">
      <div  class="product-item">
        <div  class="product-image">
          <img src="https://ecuniplatform-static.kiehls.com.cn/product/20211028010/903372841443921920/PRODUCT_150_150/RATIO/12_1-UFC-50ML_TCN03386.jpg" alt="" >
        </div>
        <div class="product-detail">
            <p  class="product-name">科颜氏高保湿霜</p>
            <div  class="heart-main">
              <span>♥</span><span>♥</span><span>♥</span><span>♥</span><span>♥</span>
            </div>
            <p  class="product-price">¥315 - ¥580</p>
          </div>
        </div>
        <div  class="product-item">
          <div  class="product-image">
          <img src="https://ecuniplatform-static.kiehls.com.cn/medias/12_5-%E9%87%91%E6%B0%B4-250ML_S0926301U_e7bfd07e9c8543f68a8383b263ab651b/PRODUCT_150_150/RATIO/12_5-%E9%87%91%E6%B0%B4-250ML_S0926301U.jpg" alt="" >
          </div>
          <div  class="product-detail">
            <p  class="product-name">科颜氏金盏花爽肤水</p>
            <div  class="heart-main">
            <span>♥</span><span>♥</span><span>♥</span><span>♥</span><span>♥</span>
            </div>
            <p  class="product-price">¥340 - ¥570</p>
          </div>
        </div
        ><div  class="product-item">
          <div  class="product-image">
            <img src="https://ecuniplatform-static.kiehls.com.cn/product/20211028010/903372841443921920/PRODUCT_150_150/RATIO/12_12-CCDS%E5%AE%89%E7%99%BD%E7%93%B6-30ML_F7681100U.jpg">
          </div>
          <div  class="product-detail">
            <p  class="product-name">科颜氏新集焕白均衡亮肤淡斑精华液</p>
            <div  class="heart-main">
            <span>♥</span><span>♥</span><span>♥</span><span>♥</span><span>♥</span>
            </div>
            <p class="product-price">¥540 - ¥1300</p>

              </div>
            </div>
          
      </div>
    </div>
    </li>`
  )
);
$(".headList .cartLi")
  .css({
    overflow: "hidden",
    height: "52px",
    boxSizing: "border-box"
  })
  .find(".icon-gouwudai101")
  .css({
    color: "#fff",
    fontSize: "30px",
    textShadow: "0 0 20px #FFF"
  });
$(".headList").append(
  $(
    '<li class="userLi LiHover"><span class="iconfont icon-201yonghu_yonghu2"></span></li>'
  )
);
$(".headList .userLi")
  .css({
    overflow: "hidden",
    height: "52px",
    boxSizing: "border-box"
  })
  .find(".icon-201yonghu_yonghu2")
  .css({
    color: "#fff",
    width: "40px",
    height: "40px",
    fontSize: "28px",
  });

$(".LiHover").css("display", "none");


window.onscroll = function () {
  let scrollTop = document.documentElement.scrollTop;
  let headTopHeight = $(".head-top").outerHeight();
  if (scrollTop >= headTopHeight) {
    $(".LiHover").css("display", "block");
    $("nav").css({
      position: "sticky",
      top: "0",
      zIndex: "999999999"
    });
  } else {
    $(".LiHover").css("display", "none");
    $("nav").css({
      position: "relative",
      zIndex: "1"
    });
  }

  $(".navigation-pc").offset()
  if (scrollTop >= navigationTOP) {
    $(".navigation-pc").css({
      top: "52px",
      position: "sticky",
      zIndex: "2147483642",
    })


  } else {
    $(".navigation-pc").css({
      position: "relative",
      top: "0"
    })
  }
  if (scrollTop >= navigationTOP && scrollTop <= cp1Top) {
    $(".navigation-pc").find("img:eq(0)").css({
      display: "none"
    })
    $(".navigation-pc").find("img:eq(1)").css({
      display: "block"
    })
  } else {
    $(".navigation-pc").find("img:eq(1)").css({
      display: "none"
    })
    $(".navigation-pc").find("img:eq(5)").css({
      display: "none"
    })
    $(".navigation-pc").find("img:eq(0)").css({
      display: "block"
    })
  }

  if (scrollTop >= cp1Top && scrollTop <= cp2Top) {
    $(".navigation-pc").find("img:eq(2)").css({
      display: "none"
    })
    $(".navigation-pc").find("img:eq(3)").css({
      display: "block"
    })
  } else {
    $(".navigation-pc").find("img:eq(3)").css({
      display: "none"
    })
    $(".navigation-pc").find("img:eq(2)").css({
      display: "block"
    })
  }

  if (scrollTop >= cp2Top) {
    $(".navigation-pc").find("img:eq(4)").css({
      display: "none"
    })
    $(".navigation-pc").find("img:eq(5)").css({
      display: "block"
    })
  } else {
    $(".navigation-pc").find("img:eq(5)").css({
      display: "none"
    })
    $(".navigation-pc").find("img:eq(4)").css({
      display: "block"
    })
  }

};



$(".go-top").click(function () {
  $("html").animate({
    scrollTop: 0
  }, 400);
});


$(".user-section .user").click(function () {
  console.log(11111);
  location.href = "register.html"
})

//  更新内容 *********************
//  更新内容 *********************
//  更新内容 *********************

$("nav .left-wrap").html(`    <div>
<p class="title"> 您的购物袋有 <span class="head-all-num">0</span> 件产品 </p>
    <div class="product-ww">
        
    </div>
    <div class="total">
        <p class="total-price">总计：¥ <span class="head-all-price">0</span> </p>
        <button class="default-btn red">立即结算</button>
    </div>
</div>
`);
$(".headModule .left-wrap").html(`<div>
      <p class="title"> 您的购物袋有 <span class="head-all-num">0</span> 件产品 </p>
          <div class="product-ww">
              
          </div>
          <div class="total">
              <p class="total-price">总计：¥ <span class="head-all-price">0</span> </p>
              <button class="default-btn red">立即结算</button>
          </div>
  </div>
      `);

// var uid = localStorage.getItem("uid");
loadCartList();

function loadCartList() {
  let uid = localStorage.getItem("uid");
  const cartListAPI = "http://jx.xuzhixiang.top/ap/api/cart-list.php";
  $.ajax({
    type: "get",
    url: cartListAPI,
    data: {
      id: uid,
    },
    success: function (res) {
      console.log("loadCartList();函数执行");
      let resArr = res.data.map((v) => {
        let reg = /(.+)<br>(.+)/
        reg.test(v.pdesc)
        let arr = reg.exec(v.pdesc)
        // console.log(RegExp.$1);
        // console.log(RegExp.$2);
        let name = RegExp.$1
        let ml = RegExp.$2
        // console.log(name, ml);
        return `
                <div class="product-item">
                    <div class="item-image">
                        <img src="${v.pimg}">
                    </div>
                    <div class="item-detail">
                        <p class="name">${name}</p>
                        <p class="capacity"> ${ml}</p>
                        <div class="price-wrap">
                            <div class="quantity">
                                <p class="label">数量</p>
                                <input class="select numArr" type="number" value="${v.pnum}" onchange="numChange(this,window.event,${v.pid})">
                            </div>
                            <div class="price">
                                <p class="label">价格</p>
                                <p class="value pricePArr">${v.pprice}</p>
                            </div><button  class="delete" onclick="delClick(this,window.event,${v.pid})">删除</button>
                        </div>
                    </div>
                </div>
            `;
      });
      $(".product-ww").html(resArr);
      All()

      function All() {
        let headCartNum = [];
        let numArr = document.querySelectorAll(".navCartHover .numArr")
        // console.log(numArr);
        numArr.forEach(n => {
          // console.log(Number(n.value));

          headCartNum.push(Number(n.value))
        });
        var sumAll = headCartNum.reduce(function (sum, v) {
          return sum + v
        })
        // console.log(sumAll);
        $(".head-all-num").text(sumAll)
        document.querySelector(".shopping-text").nextElementSibling.innerText = `(${sumAll})`
        // console.log($(".navCartHover .left .product-item"))
        let ppriceAll = []
        let ppriceArr = document.querySelectorAll(".navCartHover .left .product-item")
        ppriceArr.forEach(p => {

          ppriceAll.push($(p).find(".numArr").val() * $(p).find(".pricePArr").text())

        })
        // console.log(ppriceAll);
        var price = ppriceAll.reduce(function (sum, v) {
          return sum + v
        })
        // console.log(price);
        $(".head-all-price").text(price)
      }


    },
  });
}

function delClick(btn, e, pid) {

  console.log(btn, e, pid);
  let uid = localStorage.getItem("uid");

  $.ajax({
    type: "get",
    url: "http://jx.xuzhixiang.top/ap/api/cart-delete.php",
    data: {
      uid,
      pid,
    },
    success: function (res) {
      console.log(res);
    },
  });
  // loadCartList();
  loadCartList();
  layui.use('layer', function () {
    var layer = layui.layer;
    layer.msg('删除成功');
  });
  // loadCartList();
  loadCartList();

}

function numChange(ipt, e, pid) {
  loadCartList();
  console.log("loadCartList();");
  /*
         uid  用户id
         pid  商品id
         pnum  要添加的商品数量

        */
  let pnum = $(ipt).val();
  // console.log($(ipt).val());
  if ($(ipt).val() < 1) {
    $(ipt).val(1);
    alert("不能少于一件");
  } else {
    $.ajax({
      type: "get",
      url: "http://jx.xuzhixiang.top/ap/api/cart-update-num.php",
      data: {
        uid,
        pid,
        pnum,
      },
      success: function (res) {
        console.log(res);
        loadCartList();
        // loadCartList();
      }
    });
    loadCartList();
  }

}

$(".icon-gouwudai101").click(function () {
  location.href = "cart.html"
})
$(".user-cart").click(function () {
  location.href = "cart.html"
})

//阻止默认行为
$(".popup-with-triangle").click(function (evt) {
  evt.stopPropagation()
})
$(".numArr").on("input", function () {
  loadCartList();
  console.log(1111);
})

//  配置页面跳转
$(".headList_layer_1").eq(0).click(function () {
  location.href = "index.html"
})
$(".headList_layer_1").eq(2).click(function () {
  location.href = "面部护理.html"
})
$(".headList_layer_1").eq(3).click(function () {
  location.href = "身体护理.html"
})
$(".headList_layer_1").eq(4).click(function () {
  location.href = "男士护理.html"
})
$(".headList_layer_1").eq(5).click(function () {
  location.href = "头发护理.html"
})
$(".headList_layer_1").eq(6).click(function () {
  location.href = "认识KIEHL'S.html"
})
$(".headList_layer_1").eq(7).click(function () {
  location.href = "K星人俱乐部.html"
})